import request from '@/utils/request'
import { formatImageUrl } from '@/utils/image-helper'

// 获取商品列表
export function getProducts(params) {
  // 过滤掉空字符串、null和undefined值
  const filteredParams = Object.entries(params).reduce((acc, [key, value]) => {
    // 只保留非空值参数(不为空字符串、null和undefined)
    if (value !== '' && value !== null && value !== undefined) {
      acc[key] = value;
    }
    return acc;
  }, {});
  
  console.log('过滤前的查询参数:', params);
  console.log('过滤后的查询参数:', filteredParams);
  
  return request({
    url: '/admin/products',
    method: 'get',
    params: filteredParams
  });
}

// 添加商品
export function addProduct(data) {
  console.log('API 添加商品，请求数据:', JSON.stringify(data))
  // 确保字段类型正确
  const processedData = {
    ...data,
    categoryId: data.categoryId ? parseInt(data.categoryId, 10) : null,
    originalPrice: parseFloat(data.originalPrice || 0),
    price: parseFloat(data.price || 0),
    stock: parseInt(data.stock || 0, 10),
    status: parseInt(data.status || 0, 10),
  }
  console.log('API 添加商品，处理后数据:', JSON.stringify(processedData))
  
  return request({
    url: '/admin/products',
    method: 'post',
    data: processedData
  })
}

// 修改商品
export function updateProduct(id, data) {
  console.log('API 更新商品，请求数据:', JSON.stringify(data))
  // 确保字段类型正确
  const processedData = {
    ...data,
    categoryId: data.categoryId ? parseInt(data.categoryId, 10) : null,
    originalPrice: parseFloat(data.originalPrice || 0),
    price: parseFloat(data.price || 0),
    stock: parseInt(data.stock || 0, 10),
    status: parseInt(data.status || 0, 10),
  }
  console.log('API 更新商品，处理后数据:', JSON.stringify(processedData))
  
  return request({
    url: `/admin/products/${id}`,
    method: 'put',
    data: processedData
  })
}

// 删除商品
export function deleteProduct(id) {
  return request({
    url: `/admin/products/${id}`,
    method: 'delete'
  })
}

// 更新商品状态
export function updateProductStatus(id, data) {
  // 确保状态值为数字类型
  const processedData = {
    ...data,
    status: parseInt(data.status, 10)
  };
  
  console.log('API 更新商品状态，处理后数据:', processedData);
  
  return request({
    url: `/admin/products/${id}/status`,
    method: 'put',
    data: processedData
  });
}

// 获取商品详情
export function getProductDetail(id) {
  console.log(`API 正在获取商品详情，ID: ${id}`)
  return request({
    url: `/admin/products/${id}`,
    method: 'get'
  }).then(response => {
    console.log('API 获取商品详情返回:', response)
    
    // 处理图片路径
    const data = response;
    if (data && data.code === 200 && data.data) {
      const product = data.data;
      
      // 修正封面图片URL
      if (product.cover) {
        product.cover = formatImageUrl(product.cover);
      }
      
      // 修正图库URL
      if (product.gallery && Array.isArray(product.gallery)) {
        product.gallery = product.gallery.map(img => formatImageUrl(img));
      } else if (product.gallery && typeof product.gallery === 'string') {
        try {
          // 尝试解析JSON字符串
          const galleryArray = JSON.parse(product.gallery);
          if (Array.isArray(galleryArray)) {
            product.gallery = galleryArray.map(img => formatImageUrl(img));
          } else {
            product.gallery = [formatImageUrl(product.gallery)];
          }
        } catch (e) {
          product.gallery = [formatImageUrl(product.gallery)];
        }
      }
    }
    
    return response;
  }).catch(error => {
    console.error('API 获取商品详情失败:', error)
    throw error;
  })
}